package com.esfak47.mediafetcher.core.utils;

import com.esfak47.mediafetcher.core.constants.Constants;
import com.esfak47.mediafetcher.core.event.Event;
import com.esfak47.mediafetcher.core.event.EventGroupEnum;
import com.esfak47.mediafetcher.core.event.EventSender;
import com.esfak47.mediafetcher.core.event.JobLog;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * @author tony
 * @date 2018/5/21
 */
public class JobLogSender extends Writer {

    private final PrintWriter printWriter;

    public JobLogSender(EventSender eventSender, String jobId) {
        printWriter = new PrintWriter(new BufferedWriter(new JobLogInnerWriter(eventSender, jobId)));
    }

    public void log(String content) {
        printWriter.println(content);
    }

    public void log(String content, Object ... args) {
        printWriter.printf(content + "\n", args);
    }

    @Override
    public void write(@NotNull char[] cbuf, int off, int len) throws IOException {
        this.printWriter.write(cbuf, off, len);
    }

    @Override
    public void flush() {
        printWriter.flush();
    }

    @Override
    public void close() {
        printWriter.close();
    }

    private static class JobLogInnerWriter extends Writer {
        private final EventSender eventSender;
        private final String jobId;

        JobLogInnerWriter(EventSender eventSender, String jobId) {
            this.eventSender = eventSender;
            this.jobId = jobId;
        }

        @Override
        public void write(@NotNull char[] cbuf, int off, int len) throws IOException {
            if (eventSender == null) {
                throw new IOException("eventSender is null");
            }
            eventSender.send(new Event(EventGroupEnum.JOB,
                Constants.JobSubjects.log.name(), new JobLog(jobId, new String(cbuf, off, len))));
        }

        @Override
        public void flush() throws IOException {
            if (eventSender == null) {
                throw new IOException("eventSender is null");
            }
        }

        @Override
        public void close() throws IOException {
            if (eventSender == null) {
                throw new IOException("eventSender is null");
            }
        }
    }
}
